package com.fangs.yehwangglobal.widget.loading

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.fangs.yehwangglobal.R

/**
 * 公共显示加载框
 */
class LoadingPopup private constructor(
    contentView: View?,
    width: Int,
    height: Int,
    focusable: Boolean
) : PopupWindow(contentView, width, height, focusable) {

    private lateinit var root: View
    private val handler: Handler by lazy { Handler() }
    private val runnable: Runnable by lazy {
        Runnable {
            try {
                if (!isShowing) {
                    if (root.windowToken != null) {
                        showAtLocation(root, Gravity.NO_GRAVITY, 0, 0)
                    }
                } else {
                    dismiss()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    init {
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        isOutsideTouchable = true
        isTouchable = true
    }

    companion object {
        fun getInstance(context: Context): LoadingPopup {
            return LoadingPopup(
                View.inflate(context, R.layout.loging_dialog_layout, null),
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
                true
            )
        }
    }

    fun showNow(root: View) {
        this.root = root
        handler.removeCallbacks(runnable)
        handler.postDelayed(runnable, 500)
    }

    fun dismissNow() {
        handler.removeCallbacks(runnable)
        if (isShowing) {
            handler.postDelayed(runnable, 500)
        }
    }

    override fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
        /**
         * 由于此处LoadingPopup的延迟弹出机制 容易触发android.view.WindowManager$BadTokenException
         * 捕获下异常 避免程序崩溃
         */
        try {
            super.showAtLocation(parent, gravity, x, y)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}


